package com.xiaohe.gulimall.product.service.impl;

import com.xiaohe.common.constant.ProductConstant;
import com.xiaohe.common.to.SkuHasStockTo;
import com.xiaohe.common.to.SkuReductionTo;
import com.xiaohe.common.to.SpuBoundTo;
import com.xiaohe.common.to.es.SkuEsModel;
import com.xiaohe.common.utils.R;
import com.xiaohe.gulimall.product.entity.*;
import com.xiaohe.gulimall.product.feign.CouponFeignService;
import com.xiaohe.gulimall.product.feign.SearchFeignService;
import com.xiaohe.gulimall.product.feign.WareFeignService;
import com.xiaohe.gulimall.product.service.*;
import com.xiaohe.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

//    @GlobalTransactional//开启分布式事务
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1、保存基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2、保存spu的描述信息   pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //保存spuId
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        //3、保存Spu的图片集 pms_spu_images
        //获取图片
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //4、保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> valueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            valueEntity.setAttrValue(attrEntity.getAttrName());
            valueEntity.setAttrName(item.getAttrValues());
            valueEntity.setQuickShow(item.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(valueEntities);

        //远程调用
        //5、保存spu的积分信息 sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程调用，保存spu积分信息失败");
        }
        //5、保存当前spu对应的sku信息
        //5.1、sku的基本信息pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus !=null && skus.size()>0){
            skus.forEach(item->{
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    defaultImg = image.getImgUrl();
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(items -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(items.getImgUrl());
                    skuImagesEntity.setDefaultImg(items.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true是需要，false被剔除
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2、sku图片信息 pms_sku_images
                skuImagesService.saveBatch(skuImagesEntities);
                //5.3、sku销售属性的值 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setAttrId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect);
                //5.4、保存sku的优惠满减信息  sms_sku_ladder   sms_sku_full_reduction sms_member_price sms_spu_bounds
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()<=0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) ==1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程调用，保存sku积分信息失败");
                    }
                }

            });
        }


    }

    //保存基本信息 pms_spu_info
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
      this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * status:
         * key:
         * brandId: 0
         * catelogId: 225
         */
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");

        if (!StringUtils.isEmpty(key)){
            //模糊检索
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        if(StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catelog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {


        //1、组装需要的数据
        //查询出当前spuId对应的sku信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        List<Long> spuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());;        //TODO 4、查询当前sku的所以有可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttrList = productAttrValueService.baseAttrList(spuId);
        List<Long> attrIds = baseAttrList.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<SkuEsModel.Attrs> attrs =new ArrayList<>();
        List<Long> searchAttrIds = attrService.selectSearchAttrsIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrList.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());
        //封装每个sku的信息
        //TODO 1、发送远程调用查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R<List<SkuHasStockTo>> skusHasStock = wareFeignService.getSkusHasStock(spuIds);
            List<SkuHasStockTo> data = skusHasStock.getData();
            stockMap = data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, item ->
                    item.getHasStock()
            ));
        }catch (Exception e){
            log.info("库存服务查询异常:原因{}",e.getMessage());
        }
        //上架的商品集合
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProduct = skuInfoEntities.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //库存
            //设置库存信息
            if(finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //TODO 2、热度评分，0
            skuEsModel.setHotScore(0L);
            //TODO 3、品牌和分类的名字
            BrandEntity brand = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(category.getName());
            //设置检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5、将数据发送给Es
        R r = searchFeignService.productStatusUp(upProduct);
        if(r.getCode() == 0){
            log.info("远程调用成功");
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            log.error("远程调用失败");
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long id) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(id);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }

}